package com.mantru.iotpot.modbus;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.util.Base64;
import com.mantru.iotpot.eventbus.EventMessage;
import org.greenrobot.eventbus.EventBus;
import net.sourceforge.pinyin4j.PinyinHelper;

//这里放一些常用的公共的常量、函数
public class Common {
    //打包时间
    public static String Build_APK_Time = "2025-03-24 11:08";
    //本地自定义广播
    public static  String LOCAL_ACTION = "myaction";
    //sd卡建一个目录
    public static String DirName = "aa";
    //api服务器地址
    public static String API_Server_Url = "http://iotapi.mantru.com/app_api.aspx";
    //file服务器地址
    public static String File_Server_Url = "http://iotapi.mantru.com";
    //本地h5地址
    public static String Local_H5_Url = "file:///android_asset/";
    //public static String Local_H5_Url = "http://robot.mantru.com/";
    //1-11号泵对应的中文名称
    //2026.06.05  黎工要求“动物油A、动物油B”只保留1个“动物油”，洗锅水去掉
    //public static String[] nozzle_name_list = {"", "生抽", "老抽", "蚝油", "动物油A", "动物油B", "植物油", "盐水", "醋", "淀粉水", "烹饪水", "洗锅水"};
    public static int[] nozzle_id_list = {0, 1, 2, 3, 4, 6, 7, 8, 9, 10};
    public static String[] nozzle_name_list = {"", "生抽", "老抽", "蚝油", "动物油", "植物油", "盐水", "醋", "淀粉水", "烹饪水"};
    public static int[] nozzle_address_list = {0, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB};
    //要解码上报的43个地址
    public static int[] upload_address_int = {0x0027,0x0029,0x002A,0x002B,0x002C,0x002D,0x002F,0x0031,0x0033,0x0035,0x0036,0x0037,0x0038,0x0039,0x003A,0x003B,0x003C,0x003D,0x003E,0x003F,0x0040,0x0041,0x0042,0x0043,0x0046,0x0047,0x0048,0x0049,0x004A,0x004B,0x0053,0x0054,0x0055,0x0056,0x0057,0x0058,0x0059,0x005B,0x005C,0x005D,0x005E,0x005F,0x0064,0x006A};
    public static String[] upload_address_str1 = {"0x0027","0x0029","0x002A","0x002B","0x002C","0x002D","0x002F","0x0031","0x0033","0x0035","0x0036","0x0037","0x0038","0x0039","0x003A","0x003B","0x003C","0x003D","0x003E","0x003F","0x0040","0x0041","0x0042","0x0043","0x0046","0x0047","0x0048","0x0049","0x004A","0x004B","0x0053","0x0054","0x0055","0x0056","0x0057","0x0058","0x0059","0x005B","0x005C","0x005D","0x005E","0x005F","0x0064","0x006A"};
    public static String[] upload_address_str2 = {"自检报错","设备工作状态","电机工作状态","当前电压值(单位mV)","当前电流值(单位mA)","当前PWM(单位‰)","MOS温度(-40偏移)","通讯状态","当前任务号","任务报错","任务节点报错","驱动任务报错","驱动逻辑报错","正反转模式","速度档反馈","初始化状态","火力档位反馈","炒菜爪开关状态","炒菜爪寻位状态","热电偶温度(总)","1号热点偶温度","2号热点偶温度","3号热点偶温度","热点偶报错状态","位置开关状态","机械臂位置","锅口位置","投菜臂位置","平移料盒位置","泵开关状态","泵报错","当前档位","加热功率(W)","电流(0.1A)","电压(0.1V)","谐振电流","频率","相位","线盘温度","锅底温度","IGBT温度","机芯报错","芯片UID唯一码","软件版本号"};

    //是否本地打包的版本
    public static boolean IsLocalVersion()
    {
        if (Local_H5_Url.startsWith("file:"))
            return true;
        else
            return false;
    }

    //格式化本地url，如果不是http和file开头的地址则一律按本地地址处理
    public static String FormatWebUrl(String url)
    {
        if (url.length() > 0 && url.toLowerCase().trim().startsWith("http") == false && url.toLowerCase().trim().startsWith("file") == false)
            url = Local_H5_Url + url.trim();
        return url;
    }

    //读取对象列表中的第Index个对象，Index从1开始
    public static String JSON_GetRecordData(String DataStr, int Index)
    {
        String record, str;
        int count, n;
        record = "";
        count = 0;
        str = DataStr.trim();
        if (str.substring(0, 1).equals("["))
            str = str.substring(1);
        while (!str.equals("") && str.length() > 3)
        {
            n = str.indexOf("}");
            if (n >= 0)
            {
                count++;
                if (count == Index)
                {
                    record = str.substring(0, n+1);
                    break;
                }
                str = str.substring(n+1);
                if (str.substring(0, 1).equals(","))
                    str = str.substring(1);
            }
            else
                str = "";
        }
        return record;
    }

    //读取字段的值
    public static String JSON_GetFieldValue(String RecordStr, String FieldName)
    {
        String value, achar;
        int index;
        boolean aIsString = false;
        value = "";
        FieldName = "\"" + FieldName + "\":";
        index = RecordStr.indexOf(FieldName);
        if (index >= 0)
        {
            index += FieldName.length();
            achar = RecordStr.substring(index, index + 1);
            if (achar.equals("["))
            {
                RecordStr = RecordStr.substring(index);
                index = RecordStr.lastIndexOf("]");
                value = RecordStr.substring(0, index + 1);
                return value;
            }

            while (index < RecordStr.length() && (achar.equals(",") == false || (achar.equals(",") && aIsString == true)) && (achar.equals("}") == false || (achar.equals("}") == true && aIsString == true)))
            {
                if (value.equals("") == true && achar.equals("\""))
                    aIsString = true;
                if (value.equals("") == false && achar.equals("\""))
                    aIsString = false;

                value += achar;
                index++;
                if (index < RecordStr.length())
                    achar = RecordStr.substring(index, index + 1);
                else
                    achar = "}";
            }
        }

        value = value.trim();
        if (value.length() >= 1 && value.substring(0, 1).equals("\""))
            value = value.substring(1, value.length() - 1);
        if (value.length() >= 1 && value.substring(value.length() - 1, value.length()).equals("\""))
            value = value.substring(0, value.length() - 1);
        return value;
    }

    //判断url中的文件在本地缓存是否存在，是则返回本地路径
    public static String CheckUrlFileIsExists(Context context, String http_url)
    {
        String url_file_name = http_url.substring(http_url.lastIndexOf("/")+1);
        String file_name = GetFilesPath(context) + "/" + url_file_name;
        File file = new File(file_name);
        if (file.exists()) {
            if (file.length() <= 0) {
                file.delete();
                file = null;
                return "";
            }
            return file_name;
        }
        else
            return "";
    }

    //判断本地缓存文件是否存在
    public static boolean CheckLocalFileIsExists(String file_path)
    {
        File file = new File(file_path);
        if (file.exists())
            return true;
        else
            return false;
    }

    //删除本地缓存文件
    public static boolean DeleteLocalFile(String file_path)
    {
        File file = new File(file_path);
        if (file.exists()) {
            file.delete();
            return true;
        }
        else
            return false;
    }

    //重命名本地缓存文件，注意2个参数都必须是全路径
    public static boolean RenameLocalFile(String src_file_path, String dest_file_path)
    {
        File file1 = new File(src_file_path);
        if (file1.exists()) {
            File file2 = new File(dest_file_path);
            return file1.renameTo(file2);
        }
        else
            return false;
    }

    //从url中下载mp3、mp4文件并保存到本地安装目录下
    public static boolean SaveUrlToFile(Context context, String http_url)
    {
        http_url = http_url.trim();
        String file_type = http_url.substring(http_url.length() - 4).toLowerCase();
        if (http_url.length() > 4 && (file_type.equals(".png") || file_type.equals(".jpg") || file_type.equals(".gif") || file_type.equals(".bmp") || file_type.equals("jpeg") || file_type.equals(".jpeg") || file_type.equals(".apk")))
        {
            try
            {
                if (CheckUrlFileIsExists(context, http_url).length() > 0) {
                    if (http_url.endsWith(".apk")){
                        String msg = "{\"progress\":100}";
                        EventMessage e = new EventMessage(EventMessage.MSG_ID_DownApkProgress, msg);
                        EventBus.getDefault().post(e);
                        return true;
                    }
                    return false;
                }
                String url_file_name1 = http_url.substring(http_url.lastIndexOf("/")+1);
                String url_file_name2 = "temp" + url_file_name1;
                String file_name1 = GetFilesPath(context) + "/" + url_file_name1;  //这个是正式文件
                String file_name2 = GetFilesPath(context) + "/" + url_file_name2;  //这个是临时文件，下载过程中写入临时文件，完成后再重命名为正式文件
                DeleteLocalFile(file_name2);

                FileOutputStream fos = null;
                BufferedInputStream bis = null;
                HttpURLConnection httpUrl = null;
                URL url = null;
                byte[] buf = new byte[102400];   //100K的下载缓存区
                int size = 0;

                // 建立链接
                url = new URL(http_url);
                httpUrl = (HttpURLConnection) url.openConnection();
                // 设置超时
                httpUrl.setConnectTimeout(10000);   //10秒连接
                httpUrl.setReadTimeout(6000000);     //10分钟下载
                // 连接指定的资源
                httpUrl.connect();
                // 获取文件总大小，用于计算下载进度值(0-100)
                int file_size = httpUrl.getContentLength();
                int progress_old = 0, progress_new = 0;
                int down_total_size = 0;
                double rate = 0.0;
                boolean is_show_progress = file_type.equals(".apk");  //下载apk时才显示进度
                // 获取网络输入流
                bis = new BufferedInputStream(httpUrl.getInputStream());
                // 建立文件
                fos = new FileOutputStream(file_name2);
                // 保存文件
                while ((size = bis.read(buf)) != -1) {
                    fos.write(buf, 0, size);
                    //计算下载进度
                    if (is_show_progress) {
                        down_total_size += size;
                        rate = down_total_size * 100.0 / file_size;
                        progress_new = (int) rate;
                        if (progress_new != progress_old) {
                            progress_old = progress_new;
                            String msg2 = "{\"progress\":" + progress_old + "}";
                            EventMessage e2 = new EventMessage(EventMessage.MSG_ID_InitProgress, msg2);
                            EventBus.getDefault().post(e2);
                        }
                    }
                }
                fos.close();
                bis.close();
                httpUrl.disconnect();
                buf = null;
                RenameLocalFile(file_name2, file_name1);
                //如果下载的是apk安装包，则给主窗口发消息通知
                if (file_type.equals(".apk")) {
                    String msg3 = "{\"apk_path\":\"" + file_name1 + "\"}";
                    EventMessage e3 = new EventMessage(EventMessage.MSG_ID_InstallAPK, msg3);
                    EventBus.getDefault().post(e3);
                }
                return true;
            }
            catch (Exception ex)
            {
                Log("Common.SaveUrlToFile出错：" + ex.getMessage());
            }
        }
        return false;
    }

    //函数返回路径/storage/emulated/0/Android/data/包名/files
    //用来存储一些长时间保留的数据,应用卸载会被删除
    private static String GetFilesPath(Context context ){
        String file_path = "";
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
            //外部存储可用
            file_path = context.getExternalFilesDir(null).getPath();
        }else {
            //外部存储不可用
            file_path = context.getFilesDir().getPath() ;
        }
        return file_path ;
    }
    //函数返回路径file:///storage/emulated/0/Android/data/包名/files
    //用来存储一些长时间保留的数据,应用卸载会被删除
    public static String GetFilesUrl(Context context ){
        String file_path = "";
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
            //外部存储可用
            file_path = context.getExternalFilesDir(null).getPath();
        }else {
            //外部存储不可用
            file_path = context.getFilesDir().getPath() ;
        }
        return "file://" + file_path ;
    }
    //函数返回路径file:///data/data/包名/files/aa.jpg
    //用来存储一些长时间保留的数据,应用卸载会被删除
    public static String GetCacheFilesUrl(Context context, String file_name){
        //发现file:///data/data/   也访问不了文件
        //String file_path = "file:///data/data/" + context.getApplicationContext().getPackageName() + "/files/" + file_name;
        String file_path = GetFilesUrl(context) + "/" + file_name;
        return file_path;
    }
    //访问sd卡下的网址  file:///mnt/sdcard/database/taobao.html


    //判断sd卡是否存在
    public static boolean IsCardExist()
    {
        return Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }

    //获取sd卡路径
    public static String GetSDCard()
    {
        try
        {
            if (IsCardExist())
                return Environment.getExternalStorageDirectory() + "/";
            //return Environment.getExternalStorageDirectory().getCanonicalFile().toString().trim() + "/";
        }
        catch(Exception e)
        {}
        return "/mnt/sdcard/";
    }

    //写日志到sd卡指定目录
    public static void Log(String str)
    {
        if (IsCardExist() == false)
            return;
        String strDir = GetSDCard() + DirName + "/";
        try
        {
            File dir = new File(strDir);
            if (dir.exists() == false || dir.isDirectory() == false)
                dir.mkdir();
        } catch(Exception e)
        {}
        String strFileName = strDir + "Log.txt";
        Date nowDate = new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        str = "[" + format.format(nowDate) + "] " + str + "\r\n";
        System.out.println(str);
        BufferedWriter out = null;
        try
        {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(strFileName, true)));
            out.write(str);
        } catch (Exception e)
        {} finally {
            try {
                out.close();
            } catch (Exception e) {
            }
        }
    }

    //获取当前时间截，10位，单位：s
    public static long GetTimeStamp10()
    {
        return System.currentTimeMillis() / 1000;
    }
    //将YYYY-MM-DD HH:mm:ss字符串格式的时间转为时间截，10位，单位：s
    public static long GetTimeStamp10(String str_datetime)
    {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dt = format.parse(str_datetime);
            return dt.getTime() / 1000;
        }catch (Exception ex)
        {}
        return 0;
    }
    //获取当前时间截，13位，单位：ms
    public static long GetTimeStamp13()
    {
        return System.currentTimeMillis();
    }
    //将YYYY-MM-DD HH:mm:ss字符串格式的时间转为时间截，13位，单位：ms
    public static long GetTimeStamp13(String str_datetime)
    {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dt = format.parse(str_datetime);
            return dt.getTime();
        }catch (Exception ex)
        {}
        return 0;
    }
    //获取当前时间的字符串
    public static  String GetDataTimeString(){
        Date nowDate = new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = format.format(nowDate);
        return str;
    }

    //base64加密
    public static String Base64Encoder(String value){
        try {
            byte[] encodeValue = Base64.encode(value.getBytes("UTF-8"), Base64.DEFAULT);
            String return_value = encodeValue.toString();
            encodeValue = null;
            return return_value;
        }catch (Exception ex){
            return value;
        }
    }

    //将mm:ss的时间转为整数秒
    public static int time2int(String time){
        int return_value = 0;
        time = time.replace(":", ",");
        String[] list = time.split(",");
        if (list.length == 2){
            int mm = Integer.parseInt(list[0]);
            int ss = Integer.parseInt(list[1]);
            return_value = mm * 60 + ss;
        }
        return return_value;
    }
    //将整数秒转为mm:ss的时间
    public static String int2time(int second){
        String return_value = "00:00";
        int mm = second / 60;
        int ss = second % 60;
        if (mm < 10)
            return_value = "0" + mm;
        else
            return_value = "" + mm;
        if (ss < 10)
            return_value += ":0" + ss;
        else
            return_value += ":" + ss;
        return return_value;
    }

    //16进制字符串转10进制整数
    public static long hex2int(String hex_str) {
        return Long.parseLong(hex_str, 16);
    }



    //将旧版的三种锅位做个转换
    //锅位置：1洗锅位、2炒菜位、3出菜位、4回炒菜位、5停止倾倒、6恢复倾倒   2023.02.22改正为：0洗锅位、2炒菜位、1出菜位、18回炒菜位、17恢复倾倒、16停止倾倒
    public static int Convert_Pot_Position(int pot_position)
    {
        int old_position = pot_position;
        if (old_position == 1)
            pot_position = 0;
        else if (old_position == 3)
            pot_position = 1;
        else if (old_position == 4)
            pot_position = 18;
        else if (old_position == 5)
            pot_position = 16;
        else if (old_position == 6)
            pot_position = 17;
        return pot_position;
    }

    //泵控制算法，如果是开的则是左移2位+1
    //nozzle_index  是喷泵编号，1-11
    //10号11号喷泵填多少喷多少，1-9号泵填多少喷10倍
    public static int NozzleControl(int nozzle_value, int nozzle_index)
    {
        if (nozzle_value <= 0)
            return 0;
        if (nozzle_index <= 9)
            nozzle_value = nozzle_value * 10;
        int value = (nozzle_value << 2) + 1;
        return value;
    }

    //获取汉字的拼音首字母
    public static String Chinese_getFirstLetter(String hanzi) {
        StringBuilder sb = new StringBuilder();
        char[] srcChars = hanzi.toCharArray();
        for (char srcChar : srcChars) {
            // 获取每个汉字的拼音数组
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(srcChar);
            if (pinyinArray != null) {
                // 取拼音数组的第一个元素（即第一个拼音），然后取其首字母
                sb.append(pinyinArray[0].charAt(0));
            } else {
                // 如果无法转换为拼音，可以按需处理，例如返回原字符或特殊字符等
                sb.append(srcChar);
            }
        }
        return sb.toString();
    }

    //将本地缓存文件读到byte[]数组
    public static byte[] GetFile(String file_path) {
        FileInputStream fis = null;
        byte[] result = null;
        try {
            File file = new File(file_path);
            fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            buffer = null;
            result = bos.toByteArray();
            fis.close();
            bos.close();
        } catch (Exception ex) {
            Log("Common.GetFile(" + file_path + ")出错：" + ex.getMessage());
        }
        return result;
    }

    //判断字符串是否为整数
    public static boolean IsLong(String value) {
        try {
            long aa = Long.parseLong(value);
            return true;
        } catch (Exception ex) {
        }
        return false;
    }


}
